package czk.concrent.threadpool.forkandjoin.practice;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * forkAndJoin任务拆分
 *
 * @Author:ChenZhangKun
 * @Date: 2021/6/7 10:45
 */
public class ForkAndJoinPractice {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        // 创建线程池
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        SumRecursiveTask sumRecursiveTask = new SumRecursiveTask(0, 10000);
        // 执行任务
        Long invoke = forkJoinPool.invoke(sumRecursiveTask);
        System.out.println(invoke);
        System.out.println("总耗时" + (System.currentTimeMillis() - start));
    }
}

class SumRecursiveTask extends RecursiveTask<Long> {
    // 记录拆分临界值
    private static final int THRESHOLD = 3000;
    private int start;
    private int end;

    public SumRecursiveTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        // 是否大于临界值
        // 长度
        int length = end - start;
        // 是否大于临界值
        if (length > THRESHOLD) {
            // 拆分
            int middle = (start + end) / 2;
            // 左边
            System.out.println("拆分左边" + start + "到" + middle);
            SumRecursiveTask left = new SumRecursiveTask(start, middle);
            left.fork();
            System.out.println("拆分右边" + (middle + 1) + "到" + end);
            // 计算
            SumRecursiveTask right = new SumRecursiveTask(middle + 1, end);
            // 右边
            right.fork();
            return left.join() + right.join();
        } else {
            // 直接计算
            long sum = 0;
            for (int i = start; i <= end; i++) {
                sum += i;
            }
            System.out.println("计算结果=" + sum);
            return sum;
        }
    }
}
